#!/bin/sh

setup_wget()
{
	local wget
	wget=$(cmd_path wget) || return

	local wget_help=$($wget --help 2>&1)
	[ "${wget_help#*BusyBox}" != "$wget_help" ] && return 1

	http_client_cmd="$wget -q --timeout=1800 --tries=1"

	[ "${wget_help#*--local-encoding}" != "$wget_help" ] && {
		local iri_not_support="This version does not have support for IRIs"
		# $ /usr/bin/wget --local-encoding=UTF-8 /tmp/abcde
		# This version does not have support for IRIs
		$http_client_cmd --local-encoding=UTF-8 /tmp/abcde 2>&1 | grep -qF "$iri_not_support" || http_client_cmd="$http_client_cmd --local-encoding=UTF-8"
	}

	return 0
}

setup_wget_busybox()
{
	is_busybox=1

	if has_cmd wget; then
		http_client_cmd=$(cmd_path wget)
		http_client_cmd="$http_client_cmd -q"
		return
	fi

	busybox=$(cmd_path busybox) || return
	http_client_cmd="$busybox wget -q"
}

[ -n "$http_client_cmd" ] || setup_wget || setup_wget_busybox || return

if [ -n "$is_busybox" ]; then

http_get_newer()
{
	http_get_newer_can_skip "$@" && return
	http_get_file "$@"
}

http_post()
{
	local api_path="$1"
	local json_data="$2"

	if [ -n "$sched_host" ]; then # new scheduler
		local url="http://$sched_host:${sched_port:-3000}/$api_path"
	else
		local url="http://$LKP_SERVER:${LKP_CGI_PORT:-3000}/$api_path"
	fi

	$http_client_cmd --header="Content-Type: application/json" --post-data="$json_data" -O - "$url"
}

else

http_get_newer()
{
	local path="$(dirname "$2")"
	http_escape_request "$1" -N -P "$path"
}

http_post()
{
	local api_path="$1"
	local json_data="$2"

	if [ -n "$sched_host" ]; then # new scheduler
		local url="http://$sched_host:${sched_port:-3000}/$api_path"
	else
		local url="http://$LKP_SERVER:${LKP_CGI_PORT:-3000}/$api_path"
	fi

	$http_client_cmd --method=POST --header="Content-Type: application/json" --body-data="$json_data" -O - "$url"
}

fi

# common functions

http_get_file()
{
	check_create_base_dir "$2"
	http_escape_request "$1" -O "$2"
}

http_get_directory()
{
	local dir=$2
	mkdir -p $dir
	# download directory recursively
	http_do_request "$1" -c -r -np -nd -P "$dir"
}

http_get_cgi()
{
	check_create_base_dir "$2"
	http_do_request "$1" -O "${2:-/dev/null}"
}

